package com.credithc.signature.manager.utils;

import com.itextpdf.text.Document;
import com.itextpdf.text.pdf.PdfCopy;
import com.itextpdf.text.pdf.PdfDictionary;
import com.itextpdf.text.pdf.PdfName;
import com.itextpdf.text.pdf.PdfNumber;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfSmartCopy;

import java.io.FileOutputStream;

/**
 * @desc: <br/>
 * @author: Jingbo Hu<br/>
 * @time：2020年05⽉25⽇<br/>
 * @version：v1.0.0<br>
 */
public class PdfRotationUtil {


    /**
     * 切勿将源文件和输出文件使用一个路径，否则会出现异常：
     * Exception in thread "main" java.io.FileNotFoundException: (请求的操作无法在使用用户映射区域打开的文件上执行。)
     *
     * @param rotationAngel
     * @param source
     * @param dest
     */
    public static void rotatingAngel(Integer rotationAngel, String source, String dest) throws Exception {
        PdfReader reader = new PdfReader(source);
        Document document = new Document();
        FileOutputStream outputStream = new FileOutputStream(dest);
        PdfCopy pdfCopy = new PdfSmartCopy(document, outputStream);
        document.open();

        int nums = reader.getNumberOfPages();
        PdfDictionary pd;
        for (int j = 1; j <= nums; j++) {
            pd = reader.getPageN(j);
            pd.put(PdfName.ROTATE, new PdfNumber(rotationAngel));
        }
        for (int page = 0; page < nums; ) {
            pdfCopy.addPage(pdfCopy.getImportedPage(reader, ++page));
        }
        document.close();
        outputStream.close();
        reader.close();
    }

}
